<template>
  <div class="info-form">
    <el-upload  v-show="false" id="quill-upload" action="/api/qiniu/upload" name="file" multiple
      :limit="3" list-type="picture" :show-file-list="false" :before-upload="beforeUpload" :on-error="uploadError"
      :on-success="handleExceed">
      <el-button size="small" type="primary"></el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <el-form ref="infoForm" :model="infoForm" size="small" label-width="100px">
      <el-form-item label="课程封面">
        <uploadImage :isCompress="true" ref="uploadImage" v-model="infoForm.coverUrl" :photo="[infoForm.coverUrl]" :img="infoForm.coverUrl"
                      v-on:addImage="addImage" :limit=1
                      v-on:removeImage="removeImage"></uploadImage>
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName" :rules="[{
                    required: true, message: '课程名称不能为空', trigger: 'blur'
                  },{min: 2, max: 20, message: '课程名称长度在2 到 20 个字符', trigger: 'blur'}]">
        <el-input maxlength="20" clearable v-model="infoForm.courseName" size="small" placeholder="请输入课程名称"/>
      </el-form-item>
      <el-form-item label="销售价" prop="salePriced" :rules="[{
                    required: true, message: '销售价不能为空', trigger: 'blur'
                  }]">
        <el-input maxlength="20" type="number"  clearable v-model="infoForm.salePriced" size="small" placeholder="请输入销售价"/>
      </el-form-item>
      <el-form-item label="原价" prop="linePriced" :rules="[{
                    required: true, message: '原价不能为空', trigger: 'blur'
                  }]">
        <el-input maxlength="20" type="number"  clearable v-model="infoForm.linePriced" size="small" placeholder="请输入原价"/>
      </el-form-item>
      <el-form-item label="课程描述" prop="courseDescribe" :rules="[{
                    required: true, message: '描述不能为空', trigger: 'blur'
                  }]">
        <el-input   clearable v-model="infoForm.courseDescribe" size="small" placeholder="请输入课程描述"/>
      </el-form-item>

      <el-form-item label="课程内容"  v-loading="uillUpdateImg">
        <quill-editor v-model="infoForm.content" :options="editorOption" ref="myQuillEditor"
        >
        </quill-editor>
      </el-form-item>

    </el-form>
    <div style="text-align: center">
      <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium" @click="submitForm('infoForm')">提交
      </el-button>
      <el-button icon="el-icon-back" style="margin-left: 15px" size="medium" @click="closeWin('infoForm')">关闭
      </el-button>
    </div>
  </div>
</template>

<script>
  import gzhApi from '@/api/gzh/gzh'
  import uploadImage from '@/components/newUploadImage'
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{
      'header': 1
    }, {
      'header': 2
    }], // custom button values
    [{
      'list': 'ordered'
    }, {
      'list': 'bullet'
    }],
    [{
      'script': 'sub'
    }, {
      'script': 'super'
    }], // superscript/subscript
    [{
      'indent': '-1'
    }, {
      'indent': '+1'
    }], // outdent/indent
    [{
      'direction': 'rtl'
    }], // text direction

    [{
      'size': ['small', false, 'large', 'huge']
    }], // custom dropdown
    [{
      'header': [1, 2, 3, 4, 5, 6, false]
    }],

    [{
      'color': []
    }, {
      'background': []
    }], // dropdown with defaults from theme
    [{
      'font': []
    }],
    [{
      'align': []
    }],
    ['link', 'image', 'video'],
    ['clean'] // remove formatting button
  ]
  export default {
    name: "member",
    data() {
      // 手机号验证
      var phoneReg = /^1\d{10}$/
      var validatePhone = (rule, value, callback) => {
        if (value) {
          if (!phoneReg.test(value)) {
            callback(new Error('请输入正确手机号码'));
          } else {
            callback();
          }
        } else {
          callback(new Error('手机号码必填'));
        }
      };
      return {
        uillUpdateImg: false,
        editorOption: {
          modules: {
            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                'image': function(value) {
                  if (value) {
                    document.querySelector('#quill-upload input').click()
                    // alert('自定义图片')
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        paramsList:[



        ],
        addBtnLoading: false,
        // 手机号验证
        validatePhone: validatePhone,
      }
    },
    props: {
      infoForm: {
        type: Object,
        default() {
          return {};
        }
      },
    },
    created() {
    },
    mounted() {
    },
    components: {uploadImage},
    methods: {
      beforeUpload() { //上传图片之前开启loading
        this.uillUpdateImg = true
      },
      uploadError() { //图片上传失败,关闭loading
        this.uillUpdateImg = false
        this.$message.error('图片插入失败')
      },
      handleExceed(response, file, fileList) { //图片添加成功
        let quill = this.$refs.myQuillEditor.quill
        console.log(response)
        if (response.code === 200) {
          let length = quill.getSelection().index;
          // 插入图片 response.data为服务器返回的图片地址
          quill.insertEmbed(length, 'image', response.data)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
        this.fileList = fileList
        this.uillUpdateImg = false
      },
      // 移除图片
      removeImage(){
        this.infoForm.coverUrl = ''
      },
      // 添加图片
      addImage(...data){
        this.infoForm.coverUrl = data[0]
      },
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          var parmseData=this.infoForm;
          if (valid) {
            let method = 'courseAdd'
            if (this.infoForm.id) {
              method = 'courseEdit'
            }else{
              parmseData.status=1;
            }
            parmseData.linePrice=parmseData.linePriced*100;
            parmseData.salePrice=parmseData.salePriced*100;
            this.addBtnLoading = true
            gzhApi[method](parmseData).then(res => {
              this.addBtnLoading = false
              this.$refs[formName].resetFields()
              this.$message({
                type: 'success',
                message: this.infoForm.id ? '修改成功' : '添加成功'
              })
              if (this.infoForm.id) {
                // 编辑
                this.$emit('submit',1)
              }else{
                // 添加
                this.$emit('submit',0)
              }
              // 调动关闭窗体方法
              this.$emit('closeWin')
            }).catch(e => {
              this.addBtnLoading = false
            })
          }
        })
      },
      // 关闭窗体
      closeWin() {
        this.$refs['infoForm'].resetFields()
        this.$emit('closeWin')
      }
    }
  }
</script>

<style lang="less">
  .ql-editor{
    max-height:45vh;
    overflow: scroll;
  }
  .el-dialog__body{
    max-height:65vh;
    overflow: scroll;
  }

</style>
